import $ from 'jquery';
import header from './header';
import lazyload from 'lazyload-qiniu';
import navSync from '../../../vendor/navsync';
import share from '@geekpark/share-action';
import swal from 'sweetAlert';
import { isWechat } from 'mdetect';

$(function () {
  // common
  lazyload();
  header();

  $('.js-anima').addClass('anima');
  $('nav.nav').navSync({
    highlightClass: 'active'
  });
  const $rankVote = $('.js-rank-vote');
  const $productShare = $('.js-product-share');
  const $shareGuide = $('#share-guide');

  $productShare.find('.share-close').on('click', () => $productShare.removeClass('show'));

  $shareGuide.click(function() { $(this).removeClass('show') });

  $productShare.find('.share-btn').on('click', function() {
    const { text, thumb } = $productShare.data();
    const type = $(this).data('type');
    $productShare.removeClass('show');

    if (type === 'weichat') {
      if (isWechat()) {
        $shareGuide.addClass('show');
        return;
      }

      swal({
        title: '分享到微信',
        text: '<div style="margin: 10px auto; width:200px"><img style="width: 100%" src="http://7xiwib.com1.z0.glb.clouddn.com/ia-qrcode.png" /></div>',
        showConfirmButton: false,
        allowOutsideClick: true,
        html: true
      });
      return;
    }
    share.run({ type, text, thumb });
  })

  const checkExpiredAt = function(){
    const date = new Date();
    const day = ("0" + date.getUTCDate()).slice(-2);
    const month = ("0" + date.getUTCMonth()).slice(-2);
    const expired_time = localStorage.getItem('inno_expired_time');
    if (expired_time == null || expired_time.length < 4 || `${month}${day}` > expired_time) { 
      localStorage.clear(); 
      localStorage.setItem('inno_expired_time', `${month}${day}`);
    };
  }

  const appendStorage = id => {
    const voteIds = localStorage.getItem('vote') || '';
    localStorage.setItem('vote', voteIds.length == 0 ? id : `${voteIds},${id}`);
  }

  const reloadView = function(){
    const voteIds = (localStorage.getItem('vote') || '').split(',');
    if (voteIds.length == 0) return;

    $rankVote.each(function(){
      const $this = $(this);

      const id = $this.data('rankId');
      if(voteIds.indexOf(id) !== -1) {
        $this.addClass('vote-already');
        $this.text('分享');
      };
    });
  }

  $rankVote.on('click', function(){
    const $this = $(this);
    const rankId = $this.data('rankId');
    const { name, thumb } = $this.data();

    if ($this.hasClass('vote-already')) {
      $productShare.addClass('show');
      $productShare.data('text', `我在 Innoawards2016 为「${name}」投了一票，让最好的产品获得最高的荣誉，你也来为它点赞吧！`);
      $productShare.data('thumb', thumb);
      return;
    };

    $.ajax({
      url: `/ranks/${rankId}/vote`,
      method: 'POST'
    })
    .done(data => {
      $this.addClass('vote-already');
      $this.text('分享');
      swal({
        title: '投票成功',
        type: 'success',
        showCancelButton: true,
        confirmButtonText: '分享给好友',
        allowOutsideClick: true,
        cancelButtonText: "继续投票",
        confirmButtonColor: '#EAB05C'
      }, () => {
        $this.trigger('click');
      })

      appendStorage(rankId);
    })
    .fail(xhr => {
      const content = xhr.status === 401 ? '您今日已投过该产品了，去分享给更多人吧' : '网络请求失败';
      swal({
        title: 'Error',
        text: content,
        type: 'error'
      });
    });
  })

  checkExpiredAt();
  reloadView();
})
